package com.app.jzgdirector.common.service;

import java.lang.ref.WeakReference;
import java.util.Stack;

/**
 * 描述：改造Stac类，避免Activity引用导致的内存泄漏
 * 作者：xiangyang550
 * 时间：16/3/7 18:30
 * 邮箱：XIANGYANG550@pingan.com.cn
 */
public class ActivityStack<E> {

    private Stack<WeakReference<E>> stack = new Stack<WeakReference<E>>();

    /**
     * Constructs a stack with the default size of {@code Vector}.
     */
    public ActivityStack() {
    }

    /**
     * Returns whether the stack is empty or not.
     *
     * @return {@code true} if the stack is empty, {@code false} otherwise.
     */
    public boolean empty() {
        return stack.isEmpty();
    }


    public synchronized E peek() {
        WeakReference<E> reference = stack.peek();
        if (reference != null) {
            return reference.get();
        }
        return null;
    }


    public synchronized E pop() {
        final WeakReference<E> reference = stack.pop();
        if (reference != null) {
            return reference.get();
        }
        return null;
    }

    public E push(E element) {
        WeakReference<E> reference = new WeakReference<E>(element);
        stack.addElement(reference);
        return element;
    }

    public synchronized E lastElement() {
        WeakReference<E> reference = stack.lastElement();
        if (reference != null) {
            return reference.get();
        }
        return null;
    }

    public int size() {
        return stack.size();
    }

    public E remove(E element) {
        int index = search(element);
        if (index > 0) {
            stack.remove(index);
        }
        return element;
    }

    public void clear() {
        stack.clear();
    }

    public E get(int index) {

        WeakReference<E> reference = stack.get(index);
        if (reference != null) {
            return reference.get();
        }
        return null;
    }


    public synchronized int search(E element) {
        final int size = stack.size();
        if (element != null) {
            for (int i = size - 1; i >= 0; i--) {
                WeakReference<E> reference = (WeakReference<E>) stack.get(i);
                if (element.equals(reference.get())) {
                    return i;
                }
            }
        } else {
            for (int i = size - 1; i >= 0; i--) {
                WeakReference<E> reference = (WeakReference<E>) stack.get(i);
                if (reference == null || reference.get() == null) {// 如果reference或者引用的对象为null
                    return i;
                }
            }
        }
        return -1;
    }


}
